import { loginByUsername, logout, getLoginUserInfo } from '@/api/login'
import { getToken, setToken,setAdmin,getAdmin, removeToken,removeAdmin} from '@/utils/auth'
import { Message } from 'element-ui';

const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    adminId:'',
    setting: {
      articlePlatform: []
    },
     visitor: false,
     roles: [],
     perms: [],
     nick:''
  },

  mutations: {
    SET_CODE: (stintroductionate, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state,introduction ) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMS: (state, perms) => {
      state.perms = perms
    },
    SET_NICK: (state, nick) => {
        state.nick = nick
    },
    SET_USER_ID:(state, userId) =>{
      state.adminId = userId
    },
    SET_VISITOR: (state, visitor) => {
      state.visitor = visitor
    }
  },

  actions: {
      /**
       * @author qun.xu xionghoujin
       * @param commit
       * @param userInfo
       * @returns {Promise<any>}
       * @constructor
       * @desc    根据用户名登陆，在登陆时返回用户信息
       */
    LoginByUsername({ commit }, userInfo) {
      const username = userInfo.username.trim();
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password).then(response => {
          const data = response.data;
          if ( response.data.code !== 0){
            this.$message.error(response.data.msg);
              resolve(response)
          }
          setToken(data.data.token);
          commit('SET_TOKEN',data.data.token);
          resolve(response)
        });
      })
    },
      /**
       * @author qun.xu
       * @param commit
       * @param state
       * @returns {Promise<any>}
       * @constructor
       * @desc  由于用户信息存储在state，当刷新时roles可能会变化，所以需要重新获取
       */
    GetUserInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            getLoginUserInfo(state.token).then(res => {
              let result = res.data;
              if(result.code==0){
                  if(!result.data.perms||result.data.perms.length==0){
                      //设置访客权限
                      commit('SET_VISITOR', true);
                  }else{
                      commit('SET_VISITOR', false);
                  }
                  commit('SET_ROLES', result.data.roles);
                  commit('SET_PERMS', result.data.perms);
                  commit('SET_NICK', result.data.nickName);
                  commit('SET_NAME', result.data.name);
                  commit('SET_AVATAR', result.data.headImg);
                  resolve(res)
              }else if(result.code==997){
                this.$message.error(result.msg);
              }
            });
        });


      return new Promise((resolve, reject) => {
        getUserInfo(state.adminId).then(response => {
          let d = response.data;
          if (d.code!==0) {
            reject('error')
          }
          let roles = d.data.roles;
          if (roles && roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES',roles)
          } else {
            reject('getInfo: roles must be a non-null array !')
          }
          commit('SET_NAME',d.data.name)
          commit('SET_AVATAR',d.data.headImg)
          commit('SET_INTRODUCTION',d.data.sign)
          resolve(response)
        })
      })
    },

    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          //清空state中的token和角色
          commit('SET_TOKEN', '');
          commit('SET_ROLES', []);
          commit('SET_PERMS', []);
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },
    // 动态修改权限
    ChangeRoles({ commit, dispatch }, role) {
      return new Promise(resolve => {
        commit('SET_TOKEN', role)
        setToken(role)
        getUserInfo(role).then(response => {
          const data = response.data
          commit('SET_ROLES', data.roles)
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          dispatch('GenerateRoutes', data) // 动态修改权限后 重绘侧边菜单
          resolve()
        })
      })
    }
  }
}

export default user
